/**
 * Created by sjg on 16/12/26.
 */
var express = require('express');
var router = express.Router();
var superagent = require('superagent');
var async = require('async');
var moment = require('moment');
var CONFIG = require('../../common/config');
var checkUtil = require('./util/checkUtil');
var printUtil = require('./util/printUtil');
var CODE = require('../../common/code');


//---------------------------------接口模拟修改---------------------------------
/**
 * 获取印品列表
 * 参数: device	 0表示从pc来的请求1表示ios/2表示android/3标示app 嵌入网页/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: uuid	 设备唯一标识
 * 参数: userId	 用户唯一标识
 * 参数: typeM	 二级分类   40100: 名片  40200: 传单
 * 参数: typeL    一级分类    0 未分类   1 海报  2 多页  3 ppt.  4. 印品
 * 参数: pageNum	 请求页
 * 参数: pageSize	 请求页大小
 *
 * 返回:
 * {"success":1,
 *  "msg":"成功",
 *  "data":{
 *      "list":[
 *          {
 *              "id":123
 *              "thumb":"http://itbour-generate.img-cn-hangzhou.aliyuncs.com/image/U11/2016/11/22/102001731_xVhZWGl89XZlgzubQIkZ/0.jpg",
 *              "title":"xx蓝色商务",
 *              "price":"7元/盒 起"
 *          }
 *      ]
 *   }
 * }
 * 测试地址：http://localhost:3000/print/getPrintList?device=1&uuid=2&userId=1&typeM=40100&typeL=4
 * */
function getPrintList(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var typeM = checkUtil.numberFromReq(req, 'typeM');
    if(!typeM) {
        return printUtil.ret_func_json(0,CODE.TYPE_M_EMPTY,{},res);
    }
    var typeL = checkUtil.numberFromReq(req, 'typeL');
    if(!typeL) {
        return printUtil.ret_func_json(0,CODE.TYPE_L_EMPTY,{},res);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    printUtil.getPrintList(typeM, pageNum, pageSize, function(error, list){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{'list':list},res);
    });

}
router.get('/getPrintList', getPrintList);
router.post('/getPrintList', getPrintList);

//------------------------------------------------------------------


/**
 *获取印品商品预览信息
 *
 * 参数: device	"0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: id	印品 id
 * 返回:
 * {
 *     "success":1,
 *     "msg":"成功",
 *     "data":{
 *         "id":987,
 *         "designId":12,
 *         "thumbs":[
 *             "http://oss-image",
 *             "http://oss-image"
 *         ],
 *         "designer":{
 *             "avatarUrl":"http://oss-image",
 *             "id":358
 *         },
 *         "printPara":[
 *             {
 *                 "title":"套餐一",
 *                 "desc":"简介",
 *                 "size":{
 *                      "width":320,
 *                      "height":480,
 *                      "unit":"mm",
 *                      "desc":"A4大小"
 *                 },
 *                 "counts":[
 *                     {
 *                         "show":2,
 *                         "minCount":2,
 *                         "maxCount":10,
 *                         "price":10,
 *                         "unit":"盒"
 *                     },
 *                     {
 *                         "show":11,
 *                         "minCount":11,
 *                         "maxCount":20,
 *                         "price":9,
 *                         "unit":"盒"
 *                     }
 *                 ]
 *             }
 *         ],
 *         "productionPeriod": "72h内发货", //v5.5
 *     }
 * }
 * 测试地址：http://localhost:3000/print/getPrintPriview?device=1&uuid=2&userId=1&typeM=40100&typeL=4&id=7
 * */
function getPrintPriview(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    //var uuid = checkUtil.stringFromReq(req, 'uuid');
    //if(!uuid) {
    //    return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    //}
    //var userId = checkUtil.numberFromReq(req, 'userId');
    //if(!userId) {
    //    return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    //}
    var id = checkUtil.numberFromReq(req, 'id');
    if(!id) {
        return printUtil.ret_func_json(0,CODE.GOODS_ID_EMPTY,{},res);
    }

    printUtil.getItemAccessoryItemsId_v5_2(id, function(error, accessoryItemsId){

        var ids = id;
        if(accessoryItemsId) {

            var accIds = accessoryItemsId.toString().split(',');
            accIds = accIds.join(',');
            ids = ids + ',' + accIds;
        }
        // 串行获取数据
        async.series([
                function(callback){
                    // 获取印品信息和用户信息
                    printUtil.get_printItemAndUserInfo(id, function(error,data){ callback(error,data)});
                },
                function(callback){
                    // 获取印刷参数列表
                    //printUtil.get_printPara(id, function(error,data){ callback(error,data)});
                    printUtil.get_itemsPrintParam_v5_2(ids, function(error,data){callback(error,data)});
                }
            ],

            function(err, results){
                if(err){
                    console.log(err);
                    return printUtil.ret_func_json(0,'error',{},res);
                }

                var data = {
                    "id":               id,
                    "designId":         results[0].designId,
                    "thumbs":           results[0].thumbs,
                    "designer":         results[0].designer,
                    "printPara":        results[1],
                    "productionPeriod": "72h内发货",
                };
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
            });
    });

}
router.get('/getPrintPriview', getPrintPriview);
router.post('/getPrintPriview', getPrintPriview);

//------------------------------------------------------------------

/**
 * 创建印品默认订单
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	 用户唯一标识
 * 参数: docId	 用户作品唯一标识
 * 返回： {
 *            "success":1,
 *            "msg":"成功",
 *            "data":{
 *                "orderId":989,
 *                "orderNo":"xvawef123434"
 *            }
 *        }
 * 测试：http://localhost:3000/print/createDefaultOrder?device=1&uuid=1&userId=13&docId=45696
 * */

function createDefaultOrder(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var docId = checkUtil.numberFromReq(req, 'docId');
    if(!docId) {
        return printUtil.ret_func_json(0,CODE.DOC_ID_EMPTY,{},res);
    }
    // 此接口
    var orderType = CONFIG.ORDER_TYPE_DB_TRADE;
    // 根据地址创建默认订单
    function create_defalut_order_with_addressId(newDocId, addressId) {
        // 1、获取商品费用等信息：印刷制作费＋设计费＋邮费
        printUtil.getDefaultOrderItemInfo(newDocId, function(error, fee){
            // fee为对象，包含以下属性：productFee, designFee, mailFee
            if(error){
                console.log(error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            if(!fee){
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            // 2、创建订单和子订单
            printUtil.createDefaulPrintOrder(device, userId, newDocId, addressId, fee, function(error, newOrderInfo){
                if(error){
                    console.log(error);
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }
                if(!newOrderInfo || !newOrderInfo.orderId){
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,newOrderInfo,res);
            });
        });
    }

    // 0、检查模版信息
    printUtil.getDesignInfoByUserDocId(docId, function(getErr,retInfo){
        if(getErr){
            console.log(getErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(retInfo && retInfo.length>0){
            var designInfo = retInfo[0];
            if(Number(designInfo.publish||'0') == 1){
                // 1、复制用户文档（新文档的purpose设置为2）
                printUtil.copyUserDocForPrintOrder(docId, function (error, newDocId) {
                    if(error){
                        console.log(error);
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }
                    if(!newDocId){
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }

                    // 2、取得用户对应的收货地址（没有则为null）
                    printUtil.getUserAddress(userId, function(error, addressId){
                        if(error){
                            console.log(error);
                            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                        }

                        // 3.如果存在地址, 则拷贝地址
                        if(addressId == null) {
                            create_defalut_order_with_addressId(newDocId, null);
                        } else {
                            printUtil.copyAddress(addressId, orderType, function(error, newAddressId){
                                if(newAddressId){
                                    create_defalut_order_with_addressId(newDocId, newAddressId)
                                }else{
                                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{newAddressId:newAddressId},res);
                                }
                            });
                        }
                    });
                });

            } else {
                return printUtil.ret_func_json(0,'该模版正在升级维护中，请稍后再试',{},res);
            }

        } else {
            return printUtil.ret_func_json(0,'未获取到对应模版信息',{},res);
        }
    });
}
router.get('/createDefaultOrder', createDefaultOrder);
router.post('/createDefaultOrder', createDefaultOrder);

//------------------------------------------------------------------
/**
 * 获取用户印品作品已有订单
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	 用户唯一标识
 * 参数: id	     用户作品唯一标识
 * */
function getProductOrder (req, res, next) {
    var testData = {"success":1,"msg":"成功","data":{"orderId":444,"orderNo":"QGFTNNKKDLLJ","carriage":10.2,"addressInfo":{"id":342,"phone":1887220261,"name":"呵呵哒","prov":{"id":358,"text":"湖北省"},"city":{"id":960,"text":"武汉市"},"dist":{"id":923,"text":"洪山区"},"detail":"光谷创业街10栋"},"productInfo":{"id":345,"title":"商品名","desc":"300G白卡 亚模","price":9,"count":2,"size":"A4大小(45x64)","thumb":"http://oss-image.jpg","unit":"张","total":98}}};
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(testData);
}
router.get('/getProductOrder', getProductOrder);
router.post('/getProductOrder', getProductOrder);

//------------------------------------------------------------------
/**
 * 获取新建的订单
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	 用户唯一标识
 * 参数: orderId	 订单 id
 * 参数: orderType	商品订单: 10   发票订单: 20
 * 参数: typeM	印品二级分类   40100: 名片  40200: 传单
 * 返回：
 * 	{
 * 	    "success":1,
 * 	    "msg":"成功",
 * 	    "data":{
 * 	        "orderId":444,
 * 	        "orderNo":"QGFTNNKKDLLJ",
 * 	        "addressInfo":{
 * 	            "id":342,
 * 	            "phone":1887220261,
 * 	            "name":"呵呵哒",
 * 	            "prov":{"id":358,"text":"湖北省"},
 * 	            "city":{"id":960,"text":"武汉市"},
 * 	            "dist":{"id":923,"text":"洪山区"},
 * 	            "detail":"光谷创业街10栋"
 * 	        },
 * 	        "productInfo":[{
 * 	            "id":345,                           // 作品id
 * 	            "thumb":"http://oss-image.jpg",     // 作品图片
 * 	            "qty":2,                            // 作品的数量
 * 	            "productFee":200,                   // 作品的印刷费
 * 	            "title":"商品名",            // 商品名称
 * 	            "desc":"300G白卡 亚模",      // 商品描述
 * 	            "price":100,                // 商品最低价
 * 	            "priceCount":2,             // 商品最低价对应数量
 * 	            "size":"A4大小(45x64)",     // 商品描述
 * 	            "unit":"张",                // 商品单位
 * 	            "printParaId":989,          // 商品的印刷参数id
 * 	            "detailOrderId":1,          // 商品子订单的id
 * 	        }],
 * 	        "totalDesignFee":50             // 总设计费
 * 	        "totalMailFee":50,              // 总运费
 * 	        "totalFee":300                 // 订单总费用
 * 	    }
 * 	}
 * 测试地址:http://localhost:3000/print/getPrintOrderInfo?device=1&uuid=2&userId=13&typeM=40100&orderId=2&orderType=10
 * */
function getPrintOrderInfo(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }
    var orderType = checkUtil.numberFromReq(req, 'orderType');
    if(!orderType) {
        return printUtil.ret_func_json(0,CODE.ORDER_TYPE_EMPTY,{},res);
    }


    // 串行获取数据
    async.series([
            function(callback){
                // 根据地址和数量计算子订单邮费、并更新总费用
                printUtil.calc_printOrderMailFee(orderId, function(error,data){ callback(error,data)});
            },
            function(callback){
                // 获取订单基本信息
                printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
            },
            function(callback){
                // 获取订单地址
                printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
            },
            function(callback){
                // 获取订单产品信息
                printUtil.get_printProductInfo(orderId, function(error,data){ callback(error,data)});
            }
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            if(!results || results.length==0){
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[2]){
                addressInfo = {
                    "id":results[2].addr_id,
                    "phone":results[2].mobile|| results[2].phone,
                    "mobile":results[2].mobile|| results[2].phone,
                    "name":results[2].name,
                    "prov":{"id":results[2].prov,"text":results[2].prov_name},
                    "city":{"id":results[2].city,"text":results[2].city_name},
                    "dist":{"id":results[2].dist,"text":results[2].dist_name},
                    "detail":results[2].detail
                };
            }


            // 总设计费和总运费
            var totalDesignFee = 0;
            var totalMailFee = 0;
            for(var i=0;i<results[3].length;i++){
                var one = results[3][i];
                totalDesignFee += one.designFee;
                totalMailFee += one.mailFee;
            }

            var data = {
                "orderId":orderId,
                "orderNo":results[1].order_no,
                "orderState" : results[1].state,
                "addressInfo":addressInfo,
                "productInfo":results[3],
                "totalDesignFee":totalDesignFee,
                "totalMailFee":totalMailFee,
                "totalFee":results[1].total_fee
            };
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
        });
}
router.get('/getPrintOrderInfo', getPrintOrderInfo);
router.post('/getPrintOrderInfo', getPrintOrderInfo);

//------------------------------------------------------------------
/**
 * 修改订单商品数量
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	 订单唯一标识
 * 参数: orderType	商品订单: 10   发票订单: 20
 * 参数: detailOrderId 商品子订单的id
 * 参数: count	 商品数量
 * 返回：{"success":1,"msg":"成功","data":{"orderId" : 444}}
 * 测试地址：http://localhost:3000/print/modifyGoodsCount?device=1&uuid=1&userId=13&orderId=2&orderType=10&detailOrderId=3&count=2
 * */
function modifyGoodsCount(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }
    var orderType = checkUtil.numberFromReq(req, 'orderType');
    if(!orderType) {
        return printUtil.ret_func_json(0,CODE.ORDER_TYPE_EMPTY,{},res);
    }
    var detailOrderId = checkUtil.numberFromReq(req, 'detailOrderId');
    if(!detailOrderId) {
        return printUtil.ret_func_json(0,CODE.DETAIL_ORDER_ID_EMPTY,{},res);
    }

    var count = checkUtil.numberFromReq(req, 'count');
    if(!count) {
        return printUtil.ret_func_json(0,CODE.ORDER_COUNT_EMPTY,{},res);
    }

    // 更新子订单的数量、金额，以及订单的总金额
    printUtil.updatePrintOrderCount(orderId, detailOrderId, count, function(error, newCount){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!newCount){
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{orderId:orderId},res);
    });


}
router.get('/modifyGoodsCount', modifyGoodsCount);
router.post('/modifyGoodsCount', modifyGoodsCount);

//----------------------------------------------------------------------------
/**
 * 添加收货地址
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数(可选): address	{   "mobile":1887220261,
 *                          "name":"呵呵哒",
 *                          "prov":{"id":358,"text":"湖北省"},
 *                          "city":{"id":960,"text":"武汉市"},
 *                          "dist":{"id":923,"text":"洪山区"},
 *                          "detail":"光谷创业街10栋"
 *                      }
 * 返回：
 * 	{
 * 	    "success":1,
 * 	    "msg":"成功",
 * 	    "data":{
 * 	        "id":342,
 * 	        "mobile":1887220261,
 * 	        "name":"呵呵哒",
 * 	        "prov":{
 * 	            "id":358,
 * 	            "text":"湖北省"
 * 	        },
 * 	        "city":{
 * 	            "id":960,
 * 	            "text":"武汉市"
 * 	        },
 * 	        "dist":{
 * 	            "id":923,
 * 	            "text":"洪山区"
 * 	        },
 * 	        "detail":"光谷创业街10栋"
 * 	    }
 * 	}
 *
 * 	测试地址老版(不带 type: ): http://localhost:3000/print/addAddress?device=1&userId=299188&address={"mobile":1887220261,"name":"呵呵哒","prov":{"id":358,"text":"湖北省"},"city":{"id":960,"text":"武汉市"},"dist":{"id":923,"text":"洪山区"},"detail":"光谷创业街10栋"}
 * 	测试地址新版(带 type: ): http://localhost:3000/print/addAddress?device=1&userId=299188&address={"mobile":1887220261,"name":"呵呵哒","prov":{"id":358,"text":"湖北省"},"city":{"id":960,"text":"武汉市"},"dist":{"id":923,"text":"洪山区"},"detail":"光谷创业街10栋","type":1}
 * */

function addAddress(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    //var uuid = checkUtil.stringFromReq(req, 'uuid');
    //if(!uuid) {
    //    return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    //}
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var address = checkUtil.stringFromReq(req, 'address');
    if(address) {
        address = JSON.parse(address);
    }else{
        address = {
            "mobile":null,
            "name":null,
            "prov":{
                "id":100000,
                "text":null
            },
            "city":{
                "id":100100,
                "text":null
            },
            "dist":{
                "id":100101,
                "text":null
            },
            "detail":null
        };
    }
    // 新建地址
    printUtil.addAddress(userId, address, function(error, id){
        if(error){
            console.log(error);
            var errMsg = typeof error == 'string' ? error : CODE.OPERATION_FAILED;
            return printUtil.ret_func_json(0,errMsg,{},res);
        }
        if(!id){
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{id:id},res);
    });


}
router.get('/addAddress', addAddress);
router.post('/addAddress', addAddress);

//----------------------------------------------------------------------------
/**
 * 修改收货地址
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: addressId	 地址 id
 * 参数: address 地址信息：	{"mobile":1887220261,
 *                  "name":"呵呵哒",
 *                  "prov":{"id":358,"text":"湖北省"},
 *                  "city":{"id":960,"text":"武汉市"},
 *                  "dist":{"id":923,"text":"洪山区"},
 *                  "detail":"光谷创业街10栋"
 *                  }
 * */
function modifyAddress(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    //var uuid = checkUtil.stringFromReq(req, 'uuid');
    //if(!uuid) {
    //    return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    //}
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }

    var addressId = checkUtil.numberFromReq(req, 'addressId');
    if(!addressId) {
        return printUtil.ret_func_json(0,CODE.ADDRESS_ID_EMPTY,{},res);
    }
    var address = checkUtil.stringFromReq(req, 'address');
    if(!address) {
        return printUtil.ret_func_json(0,CODE.ADDRESS_EMPTY,{},res);
    }
    address = JSON.parse(address);


    // 更新地址
    printUtil.updateAddress(addressId, address, function(error, id){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!id){
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{id:id},res);
    });
}
router.get('/modifyAddress', modifyAddress);
router.post('/modifyAddress', modifyAddress);

//----------------------------------------------------------------------------
/**
 * 删除收货地址
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: addressId	 地址 id
 * */
function removeAddress(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }

    var addressId = checkUtil.numberFromReq(req, 'addressId');
    if(!addressId) {
        return printUtil.ret_func_json(0,CODE.ADDRESS_ID_EMPTY,{},res);
    }

    // 删除地址
    printUtil.logicDelAddress(addressId,  function(error){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/removeAddress', removeAddress);
router.post('/removeAddress', removeAddress);

//----------------------------------------------------------------------------
/**
 * 获取地址信息
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: addressId	 地址 id
 * 返回：address 地址信息：
 *              {   "success":1,
 *                  "msg":"成功",
 *                  "data":{
 *                      "addressInfo":{
 *                          "id":1,
 *                          "mobile":1887220261,
 *                          "name":"呵呵哒",
 *                          "prov":{"id":358,"text":"湖北省"},
 *                          "city":{"id":960,"text":"武汉市"},
 *                          "dist":{"id":923,"text":"洪山区"},
 *                          "detail":"光谷创业街10栋"
 *                      }
 *                  }
 *               }
 * 测试地址：http://localhost:3000/print/getAddressInfo?device=1&uuid=1&userId=13&addressId=1
 * */
function getAddressInfo(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }

    var addressId = checkUtil.numberFromReq(req, 'addressId');
    if(!addressId) {
        return printUtil.ret_func_json(0,CODE.ADDRESS_ID_EMPTY,{},res);
    }

    // 获取地址
    printUtil.getAddressInfo(addressId,  function(error,address){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!address){
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{addressInfo:address},res);
    });
}
router.get('/getAddressInfo', getAddressInfo);
router.post('/getAddressInfo', getAddressInfo);


//----------------------------------------------------------------------------
/**
 * 给订单设置收货地址
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: addressId	 地址 id
 * 参数: orderId	订单id
 * 参数: orderType	商品订单: 10   发票订单: 20
 * 返回： {          "success":1,
 *                  "msg":"成功",
 *                  "data":{
 *                      "newAddressId":newAddressId
 *                  }
 *               }
 * 测试地址：http://localhost:3000/print/setOrderAddress?device=1&uuid=1&userId=13&orderId=2&orderType=10&addressId=1
 * */
function setOrderAddress(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }

    var addressId = checkUtil.numberFromReq(req, 'addressId');
    if(!addressId) {
        return printUtil.ret_func_json(0,CODE.ADDRESS_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }
    var orderType = checkUtil.numberFromReq(req, 'orderType');
    if(!orderType) {
        return printUtil.ret_func_json(0,CODE.ORDER_TYPE_EMPTY,{},res);
    }

    // 拷贝地址信息
    printUtil.copyAddress(addressId, orderType, function(error, newAddressId){
        if(newAddressId){
            // 更新订单地址
            printUtil.updateOrderAddress(orderId, orderType, newAddressId,   function(error){
                if(error){
                    console.log(error);
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
            });
        }else{
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{newAddressId:newAddressId},res);
        }
    });

}
router.get('/setOrderAddress', setOrderAddress);
router.post('/setOrderAddress', setOrderAddress);

//----------------------------------------------------------------------------
/**
 * 获取用户订单列表
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderType	商品订单: 10   发票订单: 20
 * 参数: states	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'。所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
 * 参数: pageNum	请求页
 * 参数: pageSize	请求页大小
 * 返回：
 * 	{
 * 	    "success":1,
 * 	    "msg":"成功",
 * 	    "data":{
 * 	        "orders":[
 * 	            {
 * 	                "orderId":123456789,
 * 	                "orderNo":"QGFTNNKKDLLJ",
 * 	                "state":70,
 * 	                "totalDesignFee":50,
 * 	                "totalMailFee":50,
 * 	                "totalFee":300,
 * 	                "productInfo":[
 * 	                    {
 * 	                        "id":345,
 * 	                        "thumb":"http://oss-image.jpg",
 * 	                        "qty":2,
 * 	                        "productFee":200,
 * 	                        "title":"商品名",
 * 	                        "desc":"300G白卡亚模",
 * 	                        "price":100,
 * 	                        "priceCount":2,
 * 	                        "size":"A4大小(45x64)",
 * 	                        "unit":"张",
 * 	                        "printParaId":989,
 * 	                        "detailOrderId":1
 * 	                    }
 * 	                ]
 * 	            }
 * 	        ]
 * 	    }
 * 	}
 * */
function getOrderList(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderType = checkUtil.numberFromReq(req, 'orderType');
    if(!orderType) {
        return printUtil.ret_func_json(0,CODE.ORDER_TYPE_EMPTY,{},res);
    }
    var states = checkUtil.stringFromReq(req, 'states');
    if(states) {
        states = JSON.parse(states);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;


    printUtil.getPrintOrderList(userId, states,pageNum,pageSize, function(error,data){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);

    });
}
router.get('/getOrderList', getOrderList);
router.post('/getOrderList', getOrderList);

//----------------------------------------------------------------------------
/**
 * 查看用户订单详情
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	商品订单id
 * 返回：
 * 	{
 * 	    "success":1,
 * 	    "msg":"成功",
 * 	    "data":{
 * 	        "orderId":444,
 * 	        "orderNo":"QGFTNNKKDLLJ",
 * 	        "state":70,
 * 	        "totalDesignFee":50,
 * 	        "totalMailFee":50,
 * 	        "totalFee":300,
 * 	        "addressInfo":{
 * 				"id":342,
 * 				"phone":1887220261,
 * 				"name":"呵呵哒",
 * 				"prov":{"id":358,"text":"湖北省"},
 * 				"city":{"id":960,"text":"武汉市"},
 * 				"dist":{"id":923,"text":"洪山区"},
 * 				"detail":"光谷创业街10栋"
 * 	        },
 * 	        "productInfo":[
 * 	            {
 * 	                "id":345,
 * 	                "thumb":"http://oss-image.jpg",
 * 	                "qty":2,
 * 	                "productFee":200,
 * 	                "title":"商品名",
 * 	                "desc":"300G白卡亚模",
 * 	                "price":100,
 * 	                "priceCount":2,
 * 	                "size":"A4大小(45x64)",
 * 	                "unit":"张",
 * 	                "printParaId":989,
 * 	                "detailOrderId":1
 * 	            }
 * 	        ],
 * 	        "additionalInfo":{
 *                 “createTime”:”2016-10-16",// 创建时间
 *                 “payTime”:”2016-12-1815:03”,// 支付时间，没有则null
 *                 “printTime”:”2016-12-1815:03”,// 开始印刷时间，没有则null
 *                 “mailTime”:”2016-12-1815:03”,// 开始快递时间，没有则null
 *                 “doneTime”:”2016-12-1815:03",// 完成时间，没有则null
 *                 "countdownPay":"23小时后交易自动关闭",// 支付倒计时，没有则null
 *                 "countdownDone":"5天后交易自动关闭",// 支付倒计时，没有则null
 * 	        },
 * 	        "logisticsInfo":[
 * 	            {
 * 	                "detailOrderId":1,
 * 	                "info":"[武汉市]洪山区关山大道派件员五角塘1111111111正在为您派件",
 * 	                "time":"2016-12-1916:27"
 * 	            },
 * 	            {
 * 	                "detailOrderId":1,
 * 	                "info":"[武汉市]洪山区关山大道派件员五角塘1111111111正在为您派件",
 * 	                "time":"2016-12-1916:27"
 * 	            }
 * 	        ],
 * 	        "deliveryInfo":[{
 * 	            "detailOrderId":1,
 * 	            "name":"中通快递",
 * 	            "no":9876543212345
 * 	        }]
 * 	    }
 * 	}
 * 	测试地址：http://localhost:3000/print/getOrderDetail?device=1&uuid=1&userId=13&orderId=930
 * */
function getOrderDetail(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    // 串行获取数据
    async.series([
            function(callback){
                // 获取订单基本信息
                printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***0
            function(callback){
                // 获取订单地址
                printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***1
            function(callback){
                // 获取订单产品信息
                //printUtil.get_printProductInfo(orderId, function(error,data){ callback(error,data)});
                callback(null,null);
            }, // ***2
            function(callback){
                // 获取订单附加信息
                printUtil.get_additionalInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***3
            function(callback){
                // 获取订单物流信息
                printUtil.get_logisticsInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***4
            function(callback){
                // 获取订单快递公司信息
                printUtil.get_deliveryInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***5
            function(callback){
                printUtil.get_tradeOrderDetailsInfo_v5_2(orderId, function(error,data){callback(error,data)})
            }, // ***6
            function(callback){
                printUtil.getCouponInfoByTradeOrderId_v5_2(orderId, function(error,data){callback(error,data)})
            } // ***7
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            //if(!results || results.length==0 || !results[0] || !results[2]){
            //    return printUtil.ret_func_json(0,'error',{},res);
            //}
            if(!results || results.length==0 || !results[0] || !results[6]){
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[1]){
                addressInfo = {
                    "id":results[1].addr_id,
                    "phone":results[1].mobile|| results[1].phone,
                    "mobile":results[1].mobile|| results[1].phone,
                    "name":results[1].name,
                    "prov":{"id":results[1].prov,"text":results[1].prov_name},
                    "city":{"id":results[1].city,"text":results[1].city_name},
                    "dist":{"id":results[1].dist,"text":results[1].dist_name},
                    "detail":results[1].detail
                };
            }


            // 总设计费和总运费
            var totalDesignFee = 0;
            var totalMailFee = 0;
            var totalAccesstoryFee = 0;
            //for(var i=0;i<results[2].length;i++){
            //    var one = results[2][i];
            //    totalDesignFee += one.designFee;
            //    totalMailFee += one.mailFee;
            //}
            for(var i=0;i<results[6].productInfo.length;i++){
                var one = results[6].productInfo[i];
                totalDesignFee += one.designFee;
                totalMailFee += one.mailFee;
            }
            for(var i=0;i<results[6].accesstoryInfo.length; i++){
                var one = results[6].accesstoryInfo[i];
                totalAccesstoryFee += one.accessoryFee;
                totalMailFee += one.mailFee;
            }

            var data = {
                "orderId":orderId,
                "orderNo":results[0].order_no,
                "state":results[0].state,
                "addressInfo":addressInfo,
                //"productInfo":results[2],
                "totalDesignFee":totalDesignFee,
                "totalMailFee":totalMailFee,
                "totalFee":results[0].total_fee,
                "additionalInfo":results[3],
                "logisticsInfo":results[4],
                "deliveryInfo":results[5],
                "productInfo":results[6].productInfo,
                "accessoryInfo":results[6].accesstoryInfo,
                "couponInfo" : results[7],
                "totalAccessoryFee" : totalAccesstoryFee
            };

// todo 模拟数据, 正式环境删除, 待实现, begin
//            data.accessoryInfo = [{
//                    "id" : 9,                    // 配件 id
//                    "count" : 2,                 // 配件数量
//                    "price" : 40,                // 配件单价
//                    "accessoryFee": 80,          //  本配件总费用
//                    "desc"  : "门型展架"          // 配件描述
//                }];
//            data.couponInfo = {
//                "id":986,                   // 优惠券唯一标识
//                "code":"QWERTPOIUYEV",      // 优惠券兑换码, 也可作唯一标识
//                "type_desc":"抵扣券",        // 优惠券类型描述, 抵扣券, 折扣券, 满减
//                "discount_desc":"5.0元",    // 优惠券额度, 5元 8折
//                "trade_type":20,            // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
//                "expiry_time":"2017-03-05", // 优惠券过期时间
//                "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
//                "reason":""                 // 优惠券失效原因, 未失效则为空字符串
//            };

// todo 模拟数据, 正式环境删除, 待实现, begin


            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
        });
}
router.get('/getOrderDetail', getOrderDetail);
router.get('/getOrderDetail', getOrderDetail);

//----------------------------------------------------------------------------
/**
 * 获取用户可开发票订单列表
 *
 * 参数: device  0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid    设备唯一标识
 * 参数: userId  用户唯一标识
 * 返回值:
 {
     "success":1,
     "msg":"成功",
     "data":{
         "orders":[
             {
                 "orderId":123456789,  //订单编号
                 "orderNo":1233443,  //订单编号
                 "state":70, //订单状态
                 "totalFee":300,//订单总金额
                 "productInfo":[
                     {
                         "id":345,// 作品编号
                         "thumb":"http://oss-image.jpg",//作品预览图
                         "qty":2,//作品数量
                         "productFee":200,// 作品的制作费
                         "title":”商品名",// 商品名称
                         "desc":"300G白卡亚模",// 商品描述
                         "price":100,// 商品起步价
                         "priceCount":2,// 商品起步数量
                         "size":"A4大小(45x64)",// 商品尺寸
                         "unit":"张",// 商品单位
                         "printParaId":989,// 商品印刷参数
                         "detailOrderId":1// 子订单id
                     }
                 ]
             }
         ]
     }
 }
 * */
function getInvoiceAbleOrderList(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }

    printUtil.getInvoiceAbleOrderList(userId, function(error, retOrders){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(retOrders && retOrders.length>0) {
            // 并行获取product数据
            var asyncFuncs = [];
            for (var i in retOrders) {
                asyncFuncs.push((function (index, data) {
                    return function (asyncCallback) {
                        // 获取订单产品信息
                        printUtil.get_printProductInfo(data.order_id, function(getErr,getRet){
                            //data.productInfo = getRet||[];
                            retOrders[index].productInfo = getRet||[];
                            return asyncCallback(getErr, getRet);
                        });
                    }
                })(i, retOrders[i])); // 利用闭包解决动态参数传递问题
            }
            async.parallel(asyncFuncs, function (err, results) {
                if (err) {
                    console.log('print.js [getInvoiceAbleOrderList] get Product Err: '+err);
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                var retData = [];
                for(var n=0; n<retOrders.length; n++){
                    retData.push({
                        orderId: retOrders[n].order_id,
                        orderNo: retOrders[n].order_no,
                        state: retOrders[n].state||0,
                        totalFee: retOrders[n].total_fee||0,
                        productInfo: retOrders[n].productInfo,
                        time:(new moment(retOrders[n].create_time)).format('YYYY-MM-DD')
                    });
                }

                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{orders:retData},res);
            });

        } else {
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{orders:[]},res);
        }
    });
}
router.get('/getInvoiceAbleOrderList', getInvoiceAbleOrderList);
router.post('/getInvoiceAbleOrderList', getInvoiceAbleOrderList);

//----------------------------------------------------------------------------
/**
 * 创建发票订单
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数;  ids	发票对应商品订单数组 [123, 456,789]
 * 参数: invoiceType	1表示公司，2表示个人
 * 返回：{
 *            "success":1,
 *            "msg":"成功",
 *            "data":{
 *               "invId" : 989,
 *               ”invNo”:”888xxxx”
 *             }
 *       }
 *  测试地址：http://localhost:3000/print/createInvoiceOrder?device=1&uuid=2&userId=1&ids=[2,3]
 * */
function createInvoiceOrder(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var ids = checkUtil.stringFromReq(req, 'ids');
    if(ids) {
        ids = JSON.parse(ids);
    }
    var invoiceType = checkUtil.numberFromReq(req, 'invoiceType') || 1; // 默认为1


    printUtil.createInvoiceOrder(device, userId, ids, invoiceType, function(error,data){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!data){
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);

    });
}
router.get('/createInvoiceOrder', createInvoiceOrder);
router.post('/createInvoiceOrder', createInvoiceOrder);
//----------------------------------------------------------------------------
/**
 * 查询发票订单详情
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: invId	发票订单 id
 * 返回:
 * {
 *   "success":1,
 *   "msg":"成功",
 *   "data":{
 *       "invId":444,
 *       "invNo":"QWERTYUIOOP",
 *       "state":90,
 *       "invoiceInfo":{
 *             "invoiceType" :1,// 1表示公司，2表示个人
 *             "title" : “发票抬头",
 *             “content”:"印刷费",
 *             “orderFee”:"印刷费",
 *             "taxpayerId" : "纳税人识别号",
 *             "bank" : "开户行",
 *             "bankAccount" : "对公账户",
 *             "address" : "发票地址",
 *             "mobile" : “电话"
 *             “mailFee”:”邮费",
 *             “payPlatform”:”支付平台”,//10微信, 20支付宝'
 *       },
 *       "addressInfo":{
 *           "id":342,
 *           "mobile":1887220261,
 *           "name":"呵呵哒",
 *           "prov":{
 *               "id":358,
 *               "text":"湖北省"
 *           },
 *           "city":{
 *               "id":960,
 *               "text":"武汉市"
 *           },
 *           "dist":{
 *               "id":923,
 *               "text":"洪山区"
 *           },
 *           "detail":"光谷创业街10栋"
 *       }
 *   }
 * }
 * 测试地址：http://localhost:3000/print/getInvoiceOrderDetail?device=1&uuid=2&userId=1&invId=5
 * */
function getInvoiceOrderDetail(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var invId = checkUtil.numberFromReq(req, 'invId');
    if(!invId) {
        return printUtil.ret_func_json(0,'发票ID为空',{},res);
    }

    // 串行获取数据
    async.series(
        [
            function(callback){
                // 获取发票基本信息
                printUtil.get_invoiceBaseInfo(invId, function(error,data){ callback(error,data)});
            },
            function(callback2){
                // 获取邮寄地址
                printUtil.get_invoiceAddressInfo(invId, function(error,data){ callback2(error,data)});
            }
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            if(!results || results.length==0){
                return printUtil.ret_func_json(0,'error',{},res);
            }
            // 避免非法订单号查询不到信息, 导致后续取值崩溃
            if(results[0] == null) {
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[1]){
                addressInfo = {
                    "id":results[1].addr_id,
                    "phone":results[1].mobile|| results[1].phone,
                    "name":results[1].name,
                    "prov":{"id":results[1].prov,"text":results[1].prov_name},
                    "city":{"id":results[1].city,"text":results[1].city_name},
                    "dist":{"id":results[1].dist,"text":results[1].dist_name},
                    "detail":results[1].detail
                };
            }

            var retData = {
                "invId":invId,
                "invNo":results[0].inv_no,
                "state":results[0].state,
                "invoiceInfo": {
                    "invoiceType":results[0].type,
                    "title":results[0].title||'',
                    "content":results[0].content||'',
                    "orderFee":results[0].order_fee||0,
                    "taxpayerId":results[0].taxpayer_id||'',
                    "bank":results[0].bank||'',
                    "bankAccount":results[0].bank_account||'',
                    "address":results[0].address||'',
                    "mobile":results[0].mobile||'',
                    "mailFee":results[0].mail_fee||0,
                    "payPlatform":results[0].pay_platform,
                },
                "addressInfo":addressInfo
            };
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
        }
    );
}
router.get('/getInvoiceOrderDetail', getInvoiceOrderDetail);
router.post('/getInvoiceOrderDetail', getInvoiceOrderDetail);
//----------------------------------------------------------------------------
/**
 * 修改发票订单信息
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	发票订单 id
 * 参数: info	"发票信息
 *       {
 *              "invoiceType" :1,  // 1表示公司，2表示个人
 *              "title" : "发票抬头",
 *              "content":"印刷费",
 *              "taxpayerId" : “1111", // 纳税人识别号
 *              "bank" : "开户行",
 *              "bankAccount" : "对公账户号",
 *              "address" : "发票地址",
 *              "mobile" : "电话"
 *       }
 * 返回：{
 *            "success":1,
 *            "msg":"成功",
 *            "data":{
 *               "invId" : 989
 *             }
 *       }
 *  测试地址：http://localhost:3000/print/modifyInvoiceOrder?device=1&uuid=2&userId=13&orderId=5&info={%22invoiceType%22:1,%22title%22:%22%E5%8F%91%E7%A5%A8%E6%8A%AC%E5%A4%B4%22,%22content%22:%22%E5%8D%B0%E5%88%B7%E8%B4%B9%22,%22taxpayerId%22:%221111%22,%22bank%22:%22%E5%BC%80%E6%88%B7%E8%A1%8C%22,%22bankAccount%22:%22%E5%AF%B9%E5%85%AC%E8%B4%A6%E6%88%B7%E5%8F%B7%22,%22address%22:%22%E5%8F%91%E7%A5%A8%E5%9C%B0%E5%9D%80%22,%22mobile%22:%22%E7%94%B5%E8%AF%9D%22}
 * */
function modifyInvoiceOrder(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }
    var info = checkUtil.stringFromReq(req, 'info');
    if(info) {
        info = JSON.parse(info);
    }else{
        return printUtil.ret_func_json(0,CODE.INVOICE_INFO_EMPTY,{},res);
    }

    // 更新发票订单
    printUtil.modifyInvoiceOrder(orderId,info, function(error,invId){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!orderId){
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{invId:invId},res);

    });
}
router.get('/modifyInvoiceOrder', modifyInvoiceOrder);
router.post('/modifyInvoiceOrder', modifyInvoiceOrder);
//----------------------------------------------------------------------------
/**
 * 获取发票订单列表
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: pageNum	 请求页
 * 参数: pageSize 请求页大小
 * 返回:
     {
        "success":1,
        "msg":"成功",
        "data":{
            "list":[
                {
                    "id":990,
                    "no":11,
                    "time":"2016-12-18",
                    "totalFee":980,
                    "state":90,
                    "content":"宣传物料印刷费",
                    "deliveryInfo":{
                        "name":"中通快递",
                        "no":9876543212345
                    }
                }
            ]
        }
     }

 测试地址: http://localhost:3000/print/getInvoiceList?device=1&uuid=1&userId=299188&pageNum=0&pageSize=12
 * */
function getInvoiceList(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;

    // 获取发票列表, 若没有数据 data 返回为 null
    printUtil.getInvoiceList(userId,pageNum,pageSize, function(error,data){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        var ret = {};
        if(data != null) {
            ret.list = data;
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);

    });
}
router.get('/getInvoiceList', getInvoiceList);
router.post('/getInvoiceList', getInvoiceList);
//----------------------------------------------------------------------------
/**
 * 获取全国省份列表
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * */
function getProvinceList(req, res, next) {
    var testData = {"success":1,"msg":"成功","data":{"list":[{"id":358,"text":"湖北省"},{"id":358,"text":"湖北省"}]}};
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(testData);
}
router.get('/getProvinceList', getProvinceList);
router.post('/getProvinceList', getProvinceList);

//----------------------------------------------------------------------------
/**
 * 获取对应省的市区列表
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: provId	 省份 id
 * */
function getCityList(req, res, next) {
    var testData = {"success":1,"msg":"成功","data":{"list":[{"id":358,"text":"武汉市"},{"id":358,"text":"武汉市"}]}};
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(testData);
}
router.get('/getCityList', getCityList);
router.post('/getCityList', getCityList);

//----------------------------------------------------------------------------
/**
 * 获取对应市区的区县列表
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: provId	 省份 id
 * 参数: cityId	市区 id
 * */
function getDistList(req, res, next) {
    var testData = {"success":1,"msg":"成功","data":{"list":[{"id":358,"text":"洪山区"},{"id":358,"text":"武江夏区"}]}};
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(testData);
}
router.get('/getDistList', getDistList);
router.post('/getDistList', getDistList);

//----------------------------------------------------------------------------
/**
 * 获取商品套餐的数量价格信息
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	订单 id
 * 参数: printParaId	 套餐 id
 * 返回:
 {
     "success":1,
     "msg":"成功",
     "data":{
         "counts":[
             {
                 "priceCount":2,
                 "minCount":2,
                 "maxCount":10,
                 "price":10,
                 "unit":"盒"
             },
             {
                 "priceCount":11,
                 "minCount":11,
                 "maxCount":20,
                 "price":9,
                 "unit":"盒"
             }
         ]
     }
 }
 * */
function getGoodsPriceCounts(req, res, next){

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var ppId = checkUtil.numberFromReq(req, 'printParaId');
    if(!ppId) {
        return printUtil.ret_func_json(0,'印刷参数ID为空',{},res);
    }

    printUtil.getPrintParamQtyPriceInfo(userId,ppId,function(error,data){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{counts:data},res);
    });
}
router.get('/getGoodsPriceCounts', getGoodsPriceCounts);
router.post('/getGoodsPriceCounts', getGoodsPriceCounts);


//----------------------------------------------------------------------------
/**
 * 用户确认收货
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	订单 id
 * 返回:
 * {"success":1,"msg":"成功","data":{}}
 * 测试地址：http://localhost:3000/print/confirmOrder?device=1&uuid=2&userId=13&orderId=2
 **/
function confirmOrder(req, res, next){

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    printUtil.confirmOrder(userId,orderId,function(error){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/confirmOrder', confirmOrder);
router.post('/confirmOrder', confirmOrder);
//----------------------------------------------------------------------------

//------------------------------------------------------------------
/* 生成印刷图片.
 * 方式:GET
 * 参数:device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数:orderId:订单id的集合，以半角逗号分割，例如：1,2,3,4
 * 参数［可选］:reuse,1表示重用已经存在的印刷图
 * 参数［可选］:zoom,表示放大倍数，例如 1
 * 参数［可选］:cutBleed,表示对出血区域的处理方式，例如 1:裁掉出血,0:带3mm出血,-1:带2mm出血,-2:带1mm出血
 * 返回: {    "success":1,
 *           "msg":"成功",
 *           "data":[{
 *              orderId:1,
 *              list:[{
 *                  detailId:1,
 *                  images:[
 *                      "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U3/2017/01/12/160442068_r9I1PqulmTQ5kzc5gHA3/0.jpg",
 *                      "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U3/2017/01/12/160442068_r9I1PqulmTQ5kzc5gHA3/1.jpg"
 *                  ]
 *              }]
 *           }]
 *       }
 * 测试地址：localhost:3000/print/createImageForPrintEx?device=1&orderId=47632
 * */
function createImageForPrintEx(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var orderId = checkUtil.stringFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }
    var reuse = checkUtil.numberFromReq(req, 'reuse') || 0;

    var zoom = checkUtil.numberFromReq(req, 'zoom') || 1;

    var cutBleed = checkUtil.numberFromReq(req, 'cutBleed') || 0;

    var ids = JSON.parse('['+orderId+']');
    if(!ids || ids.length==0) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    var asyncFuncs = [];
    for (var i in ids) {
        asyncFuncs.push((function (index, id) {
            return function (asyncCallback) {
                printUtil.createImageForPrint(id,reuse,zoom,cutBleed, function(error,images){
                    if(error){
                        console.log(error);
                        return asyncCallback(error, null);
                    }

                    return asyncCallback(error, {orderId:id,list:images});
                });
            }
        })(i, ids[i])); // 利用闭包解决动态参数传递问题
    }
    async.series(asyncFuncs, function (err, results) {
        if (err) {
            console.log('print.js [createImageForPrintEx] async Err: '+err);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        var data = [];
        for(var j in results){
            if(results[j]){
                data.push(results[j]);
            }
        }
        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
    });
}
router.get('/createImageForPrintEx', createImageForPrintEx);
router.post('/createImageForPrintEx', createImageForPrintEx);
//------------------------------------------------------------------
/* 生成印刷图片.
 * 方式:GET
 * 参数:device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数:orderId:订单id
 * 参数［可选］:reuse,1表示重用已经存在的印刷图
 * 返回: {    "success":1,
 *           "msg":"成功",
 *           "data":{
 *              orderId:1,
 *              list:[{
 *                  detailId:1,
 *                  images:[
 *                      "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U3/2017/01/12/160442068_r9I1PqulmTQ5kzc5gHA3/0.jpg",
 *                      "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U3/2017/01/12/160442068_r9I1PqulmTQ5kzc5gHA3/1.jpg"
 *                  ]
 *              }]
 *           }
 *       }
 * 测试地址：localhost:3000/print/createImageForPrint?device=1&orderId=47632
 * */
function createImageForPrint(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问


    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }
    var reuse = checkUtil.numberFromReq(req, 'reuse') || 0;

    var zoom = checkUtil.numberFromReq(req, 'zoom') || 1;

    var cutBleed = checkUtil.numberFromReq(req, 'cutBleed') || 0;


    printUtil.createImageForPrint(orderId,reuse,zoom, cutBleed,function(error,images){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{orderId:orderId,list:images},res);
    });


}
router.get('/createImageForPrint', createImageForPrint);
router.post('/createImageForPrint', createImageForPrint);
//------------------------------------------------------------------

module.exports = router;